package com.tacc.tyun.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tacc.tyun.base.BaseConstant;
import com.tacc.tyun.base.BaseServiceImpl;
import com.tacc.tyun.common.jedis.RedisService;
import com.tacc.tyun.dao.master.MsgMenuDao;
import com.tacc.tyun.model.MsgMenu;
import com.tacc.tyun.service.MsgMenuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
*
* @author congcong tao
* @date 2017/8/9 11:02
*/
@Service("msgMenuService")
public class MsgMenuServiceImpl extends BaseServiceImpl<MsgMenu> implements MsgMenuService {

    @Resource
    private MsgMenuDao msgMenuDao;

    @Autowired
    public void setBaseMapper(MsgMenuDao msgMenuDao) {
        this.baseDao = msgMenuDao;
    }

    @Autowired
    private RedisService redisService;
    private static final String REDIS_KEY = "MSG_MENU_NOT_LEAFTAG";

    private static final Integer REDIS_TIME = 60 * 60 * 24 * 30 * 3;


    @Override
    public PageInfo<MsgMenu> pageInfo(MsgMenu msgMenu, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        //通用Example查询
        Example example = new Example(MsgMenu.class);
        Example.Criteria criteria=example.createCriteria();
        if(StringUtils.isNotEmpty(msgMenu.getName())){
            criteria.andLike("name","%"+msgMenu.getName()+"%");
        }
        if (StringUtils.isNotEmpty(msgMenu.getType())){
            criteria.andEqualTo("type",msgMenu.getType());
        }
        criteria.andEqualTo("removeTag",msgMenu.getRemoveTag());
        List<MsgMenu> list=msgMenuDao.selectByExample(example);
        List<MsgMenu> msgMenuList=new ArrayList<MsgMenu>();

        //避免查询不到父类
        //TODO 按子类时间排序，无法先按父类排序再按子类排序
        if(StringUtils.isNotEmpty(msgMenu.getName())){
            //查询包括父类，包括去重
            if (list!=null && list.size()>0){
                for (MsgMenu record:list){
                    //根据id再去查询分类
                    List<MsgMenu> msgMenus = msgMenuDao.selectAllParent(record.getMenuId());
                    msgMenuList.addAll(msgMenus);
                }
            }
            //去重,效率较低
            if (!msgMenuList.isEmpty()){
                for(int i=0;i<msgMenuList.size();i++){
                    for(int j=msgMenuList.size()-1;j>i;j--){
                        if(msgMenuList.get(i).getMenuId().equals(msgMenuList.get(j).getMenuId())){
                            msgMenuList.remove(j);
                        }
                    }
                }
            }
        }else {
            msgMenuList=list;
        }
        return new PageInfo<MsgMenu>(msgMenuList);
    }

    @Override
    public int insertAndUpdateParent(MsgMenu msgMenu, MsgMenu parentMenu) {
        msgMenuDao.updateByPrimaryKeySelective(parentMenu);
        return msgMenuDao.insert(msgMenu);
    }

    @Override
    public List<MsgMenu> selectByLeafTag() {
        try {
            String cacheData = this.redisService.get(REDIS_KEY);
            if (StringUtils.isNotEmpty(cacheData)) {
                // 缓存命中
                return JSON.parseArray(cacheData, MsgMenu.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        MsgMenu record=new MsgMenu();
        record.setRemoveTag(BaseConstant.REMOVE_NO);
        record.setLeafTag(BaseConstant.MSG_MENU_NOT_LEAFTAG);
        List<MsgMenu> msgMenuList = msgMenuDao.select(record);
        try {
            // 查询的结果集写入到缓存中
            this.redisService.set(REDIS_KEY, JSON.toJSONString(msgMenuList), REDIS_TIME);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msgMenuList;
    }

    /**
     * 查询是否含有子节点，有则删除
     * @param ids
     * @param removeTag
     * @return
     */
    @Override
    public int deleteMenuByIds(List<String> ids, Integer removeTag) {
        //需要使用递归
        List<String> allIds=new ArrayList<String>();
        //需要更改状态的id
        List<String> leftIds=new ArrayList<String>();

        if (null!=ids && ids.size()>0){
            for (String id:ids){
                List<String> newIds=new ArrayList<String>();
                findAll(newIds,id);
                //将查询到的所有子ids加入到allIds中
                allIds.addAll(newIds);
            }
            allIds.addAll(ids);
        }
        //先删除
        int info=msgMenuDao.deleteMenuByIds(allIds,removeTag);

        if (null!=ids && ids.size()>0){
            for (String id:ids){
                //删除后查询，如果是末节点则更改
                //查询是否有兄弟节点，根据parentId查询
                MsgMenu msgMenu = msgMenuDao.selectByPrimaryKey(id);
                String menuParentId=msgMenu.getMenuParentId();
                MsgMenu recode=new MsgMenu();
                recode.setMenuParentId(menuParentId);
                recode.setRemoveTag(BaseConstant.REMOVE_NO);
                List<MsgMenu> list = msgMenuDao.select(recode);
                if (null==list || list.isEmpty()) {
                    //更新父节点的isParent为false
                    MsgMenu param=new MsgMenu();
                    param.setLeafTag(BaseConstant.MSG_MENU_NOT_LEAFTAG);
                    param.setMenuId(menuParentId);
                    msgMenuDao.updateByPrimaryKeySelective(param);
                }
            }
        }

        return info;
    }

    /**
     * 递归方法，利用parentId查询是否子节点
     * @param ids
     * @param parentId
     */
    private void findAll(List<String> ids, String parentId) {
        MsgMenu record=new MsgMenu();
        record.setMenuParentId(parentId);
        record.setRemoveTag(BaseConstant.REMOVE_NO);
        List<MsgMenu> list = msgMenuDao.select(record);
        if (list!=null && list.size()>0){
            for (MsgMenu msgMenu : list) {
                ids.add(msgMenu.getMenuId());
                if (StringUtils.equals(msgMenu.getLeafTag(),BaseConstant.MSG_MENU_IS_LEAFTAG)) {
                    findAll(ids, msgMenu.getMenuId());
                }
            }
        }
    }
}
